#!/bin/env python
# encoding:utf-8
"""
Tornado web server
获取通话过程中抓取的用户信息
"""
import json
import os
import sys
import traceback
import pandas as pd
import requests

sys.path.insert(0,"../")
sys.path.append("./")
sys.path.append("../")

import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpserver
import tornado.httpclient
from tornado.options import define
from tornado.options import options
import logging

current_file_path = os.path.dirname(os.path.abspath(__file__))
define("port", default=8090, help="run on the given port", type=int)

# companyId_dsType_dict = {
#     2199: '赠转魔方新信收1callFAB测试-0214_ds',
#     2225: ('星火保均分NBS1call-0331_ds','星火保人寿均分NBS1call-0407_ds','星火保均分1callFAB-0327_ds','星火保均分1callFAB-0317_ds','星火保人寿均分NBS1callB版-0417_ds')
# }


#定义获取用户目标类，输入用户信息，返回用户目标
class UserJob:
    def __init__(self,user_info,is_doudi=0):
        print('user_info:{},type:{}'.format(user_info,type(user_info)))
        if type(user_info)==str:
            try:
                user_info=user_info.strip("[]").split(", ")
            except Exception as e:
                logging.info(e)
                user_info=[]
        self.user_info=user_info
        self.user_job_default='暂时未推理出目标'
        self.is_doudi=is_doudi

    #输入用户基本信息，返回用户目标：包括家庭责任目标和用户个人健康目标
    def get_target_by_rule(self):
        cal_dict = {}
        # for tag in self.user_info:
        #     if tag.split(':')[0] in ['年龄', '婚育', '孩子年龄', '收入']:
        #         cal_dict[tag.split(':')[0]] = tag.split(':')[1]
        #         if tag.split(':')[0] in ['年龄', '孩子年龄']:
        #             try:
        #                 if tag.split(':')[1].isdigit():
        #                     cal_dict[tag.split(':')[0]] = int(tag.split(':')[1])
        #                 else:
        #                     cal_dict[tag.split(':')[0]] = tag.split(':')[1]
        #             except Exception as e:
        #                 logging.info(e)
        #                 cal_dict[tag.split(':')[0]] = tag.split(':')[1]
        cal_dict['年龄']=self.user_info['age']
        cal_dict['婚育'] = self.user_info['marriage']
        cal_dict['年收入'] = self.user_info['income']
        cal_dict['孩子年龄'] = self.user_info['child_age']
        logging.info('cal_dict:{}'.format(cal_dict))
        print('cal_dict:{}'.format(cal_dict))
        try:
            family_target_res = self.fab_target_family(cal_dict)
        except Exception as e:
            traceback.print_exc()
            family_target_res = self.user_job_default
        try:
            individual_target_res = self.fab_target_individual(cal_dict)
        except Exception as e:
            traceback.print_exc()
            individual_target_res = self.user_job_default
        if not family_target_res:
            family_target_res=self.user_job_default
        if not individual_target_res:
            individual_target_res=self.user_job_default
        logging.info('{},{}'.format(family_target_res, individual_target_res))
        print('{},{}'.format(family_target_res, individual_target_res))
        res={"家庭责任目标":family_target_res,"个人健康目标":individual_target_res}
        logging.info(res)
        print(res)
        return res
    #输入标签计算词典，返回家庭责任目标
    def fab_target_family(self,cal_dict):
        # 家庭责任目标推理
        if cal_dict.get('婚育', None):
            marry = cal_dict.get('婚育')
            if marry in ['未婚']:
                res = '抵御生病后父母赡养受影响的风险'
                return res
            if marry in ['已婚未育']:
                res = '抵御生病后配偶生活质量受影响的风险|抵御生病后父母赡养受影响的风险'
                return res
        if cal_dict.get('孩子年龄', None) and cal_dict.get('年龄', None):
            child_age = cal_dict.get('孩子年龄')
            age = cal_dict.get('年龄')
            if type(child_age) == int:
                if child_age < 18:
                    res = '抵御生病后子女抚养&教育受影响的风险|抵御生病后配偶生活质量受影响的风险|抵御生病后父母赡养受影响的风险'
                    return res
                elif child_age >= 18 and age <= 70:
                    res = '抵御生病拖累子女的风险|抵御生病后配偶生活质量受影响的风险'
                    return res
            elif type(child_age) == str:
                if child_age in ['幼儿园', '上学', '上高中', '上初中', '上小学','未满18岁']:
                    res = '抵御生病后子女抚养&教育受影响的风险|抵御生病后配偶生活质量受影响的风险|抵御生病后父母赡养受影响的风险'
                    return res
                elif child_age in ['上大学', '工作', '已毕业','18岁及以上'] and age <= 70:
                    res = '抵御生病拖累子女的风险|抵御生病后配偶生活质量受影响的风险'
                    return res
        if self.is_doudi:
            # 兜底目标推理
            if cal_dict.get('年龄', None):
                age = cal_dict.get('年龄')
                if age >= 26 and age < 30:
                    res = '抵御生病后配偶生活质量受影响的风险|抵御生病后父母赡养受影响的风险'
                elif age >= 31 and age < 45:
                    res = '抵御生病后子女抚养&教育受影响的风险|抵御生病后配偶生活质量受影响的风险|抵御生病后父母赡养受影响的风险'
                elif age >= 46:
                    res = '抵御生病拖累子女的风险|抵御生病后配偶生活质量受影响的风险'
                else:
                    res = '抵御生病后父母赡养受影响的风险'
                return res #+ '-兜底目标'
    # 输入标签计算词典，返回家庭责任目标
    def fab_target_individual(self,cal_dict):
        # 个人健康目标推理
        if cal_dict.get('年收入', None):
            income = cal_dict.get('年收入')
            if income in ['5万以下']:
                res = '抵御 没钱&借钱看大病 的风险'
                return res
            if income in ['5-20万']:
                res = '生病了可以接受更优质的医疗服务'
                return res
            if income in ['20万以上']:
                res = '生病了省下一笔巨额的全面医疗费用'
                return res
            else:
                return self.user_job_default
        if self.is_doudi:
            return '抵御 没钱&借钱看大病 的风险'


    #基于用户基础标签用规则返回用户目标
    def get_job(self,type='rule'):
        try:
            if type=='rule':
                if self.user_info==[]:
                    target=self.user_job_default
                else:
                    target=self.get_target_by_rule()
            else:
                target=self.get_target_by_gpt()
        except Exception as e:
            logging.info(e)
            print(e)
            target='未推理出目标'
        return target
    #基于用户基本信息调用gpt大模型来返回用户目标
    def get_targt_by_gpt(self):
        return ''
